<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/5/1
 * Time: 14:06
 */
namespace app\api\controller;
use app\common\controller\ApiBase;
use app\common\controller\Base;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Event;

class Wechatapi extends Base
{
    private $appid = 'wxc1c600cb9953ca42';
    private $appSecrct = 'f232aec643f584202cf647caa741a32e';
    public function wxLogin(){
        $data=input('post.');

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$this->appid.'&secret='.$this->appSecrct.'&js_code='.$data['code'].'&grant_type=authorization_code';

        $res=http_curl($url);
        $key = base64_encode($res['openid']);
        Cache::set($key,$res['session_key'], 7200);
        $res['key'] = $key;

        $pathArr = Db::name('pic')->field('path,link')->select();

        return json_encode(['res'=>$res,'path'=>$pathArr]);
    }

    public function addUserInfo(){
        $data=input('put.');

        $secrectKey = Cache::get($data['key']);

        if(! $secrectKey){
            return json_encode(['code'=>-1,'msg'=>'接口出错']);
        }

        $data['create_time'] =  $data['update_time'] = time();

        $ddata = Db::name('employee')->where('openid', $data['openid'])->find();

        if($ddata){
            Db::name('employee')->where('openid', $data['openid'])->update(['session_key'=>$secrectKey]);
            return json_encode(['code'=>1,'data'=>['uid'=>$ddata['id'],'avatarUrl'=>$ddata['avatarUrl'],'name'=>$ddata['name'], 'isPhone' => empty($ddata['phone']) ? false : true,'code'=>$ddata['code'],'isCode' => empty($ddata['channelid']) ? false : true]]);
        }else{
            $employee = new \app\common\model\Employee();
            $msg = $employee->allowfield([])->save($data);

            if($msg){
                return json_encode(['code'=>1,'data'=>['uid'=>$employee->id,'avatarUrl'=>$data['avatarUrl'],'name'=>$data['name'],'isPhone' => false]]);
            }else{
                return json_encode(['code'=>0,'msg'=>'系统出错']);
            }
        }
    }

    //登录员工信息
    public function getUserInfo(){
        $openid = input('get.openid');
        $data = Db::name('employee')->alias('a')->join('agency b','b.id = a.aid','left')->field('a.*,b.type')->where('a.openid', $openid)->find();

        if($data){
            $secrectKey = Cache::get(input('get.key'));
            Db::name('employee')->where('openid', $data['openid'])->update(['session_key'=>$secrectKey]);
            return json_encode(['code'=>1,'data'=>['uid'=>$data['id'],'avatarUrl'=>$data['avatarUrl'],'name'=>$data['name'], 'isPhone' => empty($data['phone']) ? false : true,'isCode' => empty($data['channelid']) ? false : true,'isCar'=>strpos($data['type'],'0') !== false ? true : false,'isMoto' => strpos($data['type'],'1') !== false ? true : false,'code'=>$data['code']]]);
        }else{
            return json_encode(['code'=>0,'msg'=>'查询不到该用户']);
        }
    }
}